package cn.ll.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.ll.po.Department;
import cn.ll.service.DepartmentService;

public class DepartmentAction extends Action {
	
	public void findAll(HttpServletRequest request,HttpServletResponse response){
		DepartmentService	departmentService = (DepartmentService) this.getApplicationContext().getBean("departmentService");
		List<Department>  list = departmentService.findAll();
		Map map = new HashMap(0);
		List<Map> mplist = translate2MapList(list);
		
		map.put("items", mplist);
		map.put("success", true);
		rtn(map, request, response);
		return;
	}
	
	public void save(HttpServletRequest request,HttpServletResponse response){
		String departmentName = request.getParameter("department_name");

		Department	department = new Department();
		department.setDepartmentName(departmentName);
		DepartmentService	departmentService = (DepartmentService) this.getApplicationContext().getBean("departmentService");
		departmentService.save(department);
		
		Map map = new HashMap(0);
		map.put("success", true);
		rtn(map, request, response);
		return;
	}
	
	public void update(HttpServletRequest request,HttpServletResponse response){
		String id = request.getParameter("id");
		String departmentName = request.getParameter("department_name");
		
		DepartmentService	departmentService = (DepartmentService) this.getApplicationContext().getBean("departmentService");
		Department	department = departmentService.findById(Integer.parseInt(id));
		department.setDepartmentName(departmentName);
		departmentService.update(department);
		
		Map map = new HashMap(0);
		map.put("success", true);
		rtn(map, request, response);
		return;
	}
	
	/**
	 * 将对象列表转换成map列表，每个对象只有两个值，适合下拉列表
	 * @param list
	 * @return
	 */
	private List<Map> translate2MapList(List<Department> list){
		int size = list.size();
		List<Map> list_send = new ArrayList();
		for(int i = 0;i < size; i++){
			Department department = list.get(i);
			int id = department.getId();
			Map map = new HashMap(0);
			String department_name = department.getDepartmentName();
			map.put("key", id);
			map.put("value", department_name);
			list_send.add(map);
		}
		return list_send;
	}
}
